package common

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func GetAiChatResult(messageList []MessageStruct) string {
	url := "https://ai.iextend.top/v1/chat/completions"

	requestBoy := RequestAi{
		"SparkDesk-v3.5", messageList, false,
	}
	payLoad, err := json.Marshal(requestBoy)
	if err != nil {
		SysLog("json" + err.Error())
		return ""
	}
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payLoad))
	if err != nil {
		SysLog("request fail" + err.Error())
		return ""
	}
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Authorization", "Bearer sk-ppTkHGHwNrRH87fX8bCc1928337440549997F03f6aF94390")

	client := &http.Client{}
	resp, err := client.Do(req)

	if err != nil {
		SysLog("Error sending request:" + err.Error())
		return ""
	}
	defer resp.Body.Close() // 确保在函数返回前关闭Body
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		SysLog("Error sending request:" + err.Error())
		return ""
	}
	var resultBoy ResultChat
	err = json.Unmarshal(body, &resultBoy)
	if err != nil {
		SysLog("Unmarshal fail" + err.Error())
		return ""
	}
	return resultBoy.Choices[0].Message.Content
}

// 消息数据
type MessageStruct struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

// 请求ai 的 基础结构
type RequestAi struct {
	Model    string          `json:"model"`
	Messages []MessageStruct `json:"messages"`
	Stream   bool            `json:"stream"`
}

// ai chat 返回的数据结构
type ResultChat struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Index   int `json:"index"`
		Message struct {
			Role    string `json:"role"`
			Content string `json:"content"`
		} `json:"message"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}
